<?php

namespace app\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use app\model\AdminModel;

/**
 * 验证admin 的 header token
 */
class AdminTokenRequest implements MiddlewareInterface
{
    protected $no_auth = [
        '/admin/admin/login',
        '/admin/upload/do'
    ];

    public function process(Request $request, callable $handler): Response
    {
        $path = $request->path();

        if (in_array($path, $this->no_auth) == false) {

            $authorization = $request->header('Authorization');
            // 验证token
            if (!empty($authorization)) {
                $data = explode(' ', $authorization);
                $admin = AdminModel::where('access_token', '=', $data[1])->where('status', '=', 1)->first();
                if (empty($admin)) {
                    return json(['code' => 1002, 'msg' => '请求权限不足']);
                }
                $request->admin = $admin;
            } else {
                return json(['code' => 1002, 'msg' => '请求权限不足']);
            }
        }
        return $handler($request);
    }
}
